<template>
  <div class="render-form-item">
    <!-- 输入框 -->
    <el-input
      v-if="item.type === 'input'"
      v-model="formData[item.prop]"
      :placeholder="item.placeholder || ''"
      :clearable="item.clearable !== false"
      :disabled="item.disabled"
      :readonly="item.readonly"
      :maxlength="item.maxlength"
      :show-word-limit="item.showWordLimit"
      :prefix-icon="item.prefixIcon"
      :suffix-icon="item.suffixIcon"
      :style="item.style"
      :type="item.inputType || 'text'"
      @input="handleInput"
      @change="handleChange"
      @focus="handleFocus"
      @blur="handleBlur"
    />

    <!-- 文本域 -->
    <el-input
      v-else-if="item.type === 'textarea'"
      v-model="formData[item.prop]"
      :placeholder="item.placeholder || ''"
      :clearable="item.clearable !== false"
      :disabled="item.disabled"
      :readonly="item.readonly"
      :maxlength="item.maxlength"
      :show-word-limit="item.showWordLimit"
      :rows="item.rows || 3"
      :style="item.style"
      type="textarea"
      @input="handleInput"
      @change="handleChange"
      @focus="handleFocus"
      @blur="handleBlur"
    />

    <!-- 选择器 -->
    <el-select
      v-else-if="item.type === 'select'"
      v-model="formData[item.prop]"
      :placeholder="item.placeholder || ''"
      :clearable="item.clearable !== false"
      :disabled="item.disabled"
      :multiple="item.multiple || false"
      :filterable="item.filterable || false"
      :remote="item.remote || false"
      :remote-method="item.remoteMethod"
      :loading="item.loading"
      :reserve-keyword="item.reserveKeyword !== false"
      :allow-create="item.allowCreate || false"
      :style="item.style"
      @change="handleChange"
      @visible-change="handleVisibleChange"
      @remove-tag="handleRemoveTag"
    >
      <el-option
        v-for="option in item.options"
        :key="option.value"
        :label="option.label"
        :value="option.value"
        :disabled="option.disabled"
      />
    </el-select>

    <!-- 日期选择器 -->
    <el-date-picker
      v-else-if="item.type === 'date'"
      v-model="formData[item.prop]"
      :placeholder="item.placeholder || ''"
      :clearable="item.clearable !== false"
      :disabled="item.disabled"
      :format="item.format || 'YYYY-MM-DD'"
      :value-format="item.valueFormat || 'YYYY-MM-DD'"
      :type="item.dateType || 'date'"
      :style="item.style"
      start-placeholder="开始日期"
      end-placeholder="结束日期"
      @change="handleChange"
    />

    <!-- 日期时间选择器 -->
    <el-date-picker
      v-else-if="item.type === 'datetime'"
      v-model="formData[item.prop]"
      :placeholder="item.placeholder || ''"
      :clearable="item.clearable !== false"
      :disabled="item.disabled"
      :format="item.format || 'YYYY-MM-DD HH:mm:ss'"
      :value-format="item.valueFormat || 'YYYY-MM-DD HH:mm:ss'"
      :type="item.dateType || 'datetime'"
      :style="item.style"
      start-placeholder="开始时间"
      end-placeholder="结束时间"
      @change="handleChange"
    />

    <!-- 时间选择器 -->
    <el-time-picker
      v-else-if="item.type === 'time'"
      v-model="formData[item.prop]"
      :placeholder="item.placeholder || ''"
      :clearable="item.clearable !== false"
      :disabled="item.disabled"
      :format="item.format || 'HH:mm:ss'"
      :value-format="item.valueFormat || 'HH:mm:ss'"
      :style="item.style"
      @change="handleChange"
    />

    <!-- 开关 -->
    <el-switch
      v-else-if="item.type === 'switch'"
      v-model="formData[item.prop]"
      :disabled="item.disabled"
      :active-color="item.activeColor"
      :inactive-color="item.inactiveColor"
      :active-text="item.activeText"
      :inactive-text="item.inactiveText"
      :active-value="item.activeValue || true"
      :inactive-value="item.inactiveValue || false"
      @change="handleChange"
    />

    <!-- 单选框组 -->
    <el-radio-group
      v-else-if="item.type === 'radio'"
      v-model="formData[item.prop]"
      :disabled="item.disabled"
      :size="item.size"
      @change="handleChange"
    >
      <el-radio
        v-for="option in item.options"
        :key="option.value"
        :label="option.value"
        :disabled="option.disabled"
        :border="item.border || false"
        style="margin-right: 15px;"
      >
        {{ option.label }}
      </el-radio>
    </el-radio-group>

    <!-- 多选框组 -->
    <el-checkbox-group
      v-else-if="item.type === 'checkbox'"
      v-model="formData[item.prop]"
      :disabled="item.disabled"
      @change="handleChange"
    >
      <el-checkbox
        v-for="option in item.options"
        :key="option.value"
        :label="option.value"
        :disabled="option.disabled"
        :border="item.border || false"
        style="margin-right: 15px;"
      >
        {{ option.label }}
      </el-checkbox>
    </el-checkbox-group>

    <!-- 滑块 -->
    <el-slider
      v-else-if="item.type === 'slider'"
      v-model="formData[item.prop]"
      :min="item.min || 0"
      :max="item.max || 100"
      :step="item.step || 1"
      :disabled="item.disabled"
      :show-stops="item.showStops || false"
      :show-input="item.showInput || false"
      :range="item.range || false"
      :style="item.style"
      @change="handleChange"
    />

    <!-- 评分 -->
    <el-rate
      v-else-if="item.type === 'rate'"
      v-model="formData[item.prop]"
      :max="item.max || 5"
      :disabled="item.disabled"
      :allow-half="item.allowHalf || false"
      :show-text="item.showText || false"
      :text-color="item.textColor"
      :colors="item.colors"
      :void-color="item.voidColor"
      :disabled-void-color="item.disabledVoidColor"
      @change="handleChange"
    />

    <!-- 上传 -->
    <el-upload
      v-else-if="item.type === 'upload'"
      :action="item.action"
      :headers="item.headers"
      :data="item.data"
      :name="item.name || 'file'"
      :with-credentials="item.withCredentials || false"
      :show-file-list="item.showFileList !== false"
      :drag="item.drag || false"
      :multiple="item.multiple || false"
      :accept="item.accept"
      :file-list="formData[item.prop] || []"
      :auto-upload="item.autoUpload !== false"
      :limit="item.limit"
      :on-exceed="item.onExceed"
      :on-success="handleUploadSuccess"
      :on-error="handleUploadError"
      :on-progress="handleUploadProgress"
      :on-change="handleUploadChange"
      :before-upload="item.beforeUpload"
      :before-remove="item.beforeRemove"
      :on-remove="handleUploadRemove"
      :http-request="item.httpRequest"
      :style="item.style"
    >
      <template v-if="item.drag">
        <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <div v-if="item.tip" class="el-upload__tip text-center">
          {{ item.tip }}
        </div>
      </template>
      <template v-else>
        <el-button v-if="!item.icon" :type="item.buttonType || 'primary'">
          <el-icon><Upload /></el-icon>
          {{ item.buttonText || '上传文件' }}
        </el-button>
        <el-icon v-else>{{ item.icon }}</el-icon>
      </template>
      <template #file="{ file }">
        <div>{{ file.name }}</div>
        <div v-if="file.status === 'uploading'" class="el-upload-list__item-status-label">
          <el-icon><Loading /></el-icon>
        </div>
        <div v-else-if="file.status === 'success'" class="el-upload-list__item-status-label">
          <el-icon><CircleCheckFilled /></el-icon>
        </div>
        <div v-else-if="file.status === 'fail'" class="el-upload-list__item-status-label">
          <el-icon><CircleCloseFilled /></el-icon>
          <div class="el-upload-list__item-actions">
            <span class="el-upload-list__item-retry" @click="handleUploadRetry">
              <el-icon><RefreshLeft /></el-icon>
            </span>
          </div>
        </div>
      </template>
    </el-upload>

    <!-- 自定义组件 -->
    <slot v-else-if="item.type === 'custom'" :name="item.prop" :item="item" :form-data="formData"></slot>

    <!-- 显示值 -->
    <div v-else class="display-value" :style="item.style">
      {{ formatDisplayValue() }}
    </div>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { Upload, UploadFilled, Loading, CircleCheckFilled, CircleCloseFilled, RefreshLeft } from '@element-plus/icons-vue'

// 定义组件的props
const props = defineProps({
  // 表单项配置
  item: {
    type: Object,
    required: true
  },
  // 表单数据
  formData: {
    type: Object,
    required: true
  }
})

// 定义事件
const emit = defineEmits(['input', 'change', 'focus', 'blur', 'visible-change', 'remove-tag', 'upload-success', 'upload-error', 'upload-progress', 'upload-change', 'upload-remove', 'upload-retry'])

// 处理输入
function handleInput(value) {
  emit('input', value, props.item.prop)
}

// 处理变化
function handleChange(value) {
  emit('change', value, props.item.prop)
}

// 处理焦点
function handleFocus() {
  emit('focus', props.item.prop)
}

// 处理失焦
function handleBlur() {
  emit('blur', props.item.prop)
}

// 处理选择器显示状态变化
function handleVisibleChange(visible) {
  emit('visible-change', visible, props.item.prop)
}

// 处理选择器移除标签
function handleRemoveTag(tag) {
  emit('remove-tag', tag, props.item.prop)
}

// 处理上传成功
function handleUploadSuccess(response, file, fileList) {
  if (props.item.onSuccess) {
    props.item.onSuccess(response, file, fileList)
  }
  emit('upload-success', response, file, fileList, props.item.prop)
}

// 处理上传失败
function handleUploadError(error, file, fileList) {
  if (props.item.onError) {
    props.item.onError(error, file, fileList)
  }
  emit('upload-error', error, file, fileList, props.item.prop)
}

// 处理上传进度
function handleUploadProgress(event, file, fileList) {
  if (props.item.onProgress) {
    props.item.onProgress(event, file, fileList)
  }
  emit('upload-progress', event, file, fileList, props.item.prop)
}

// 处理上传文件状态变化
function handleUploadChange(file, fileList) {
  if (props.item.onChange) {
    props.item.onChange(file, fileList)
  }
  emit('upload-change', file, fileList, props.item.prop)
}

// 处理上传文件移除
function handleUploadRemove(file, fileList) {
  if (props.item.onRemove) {
    props.item.onRemove(file, fileList)
  }
  emit('upload-remove', file, fileList, props.item.prop)
}

// 处理上传重试
function handleUploadRetry(event) {
  emit('upload-retry', event, props.item.prop)
}

// 格式化显示值
function formatDisplayValue() {
  const value = props.formData[props.item.prop]
  
  // 如果有自定义格式化函数，使用自定义函数
  if (props.item.formatter && typeof props.item.formatter === 'function') {
    return props.item.formatter(value, props.item)
  }
  
  // 根据类型格式化
  if (value === null || value === undefined || value === '') {
    return '-' // 默认空值显示
  }
  
  // 处理对象或数组
  if (typeof value === 'object') {
    if (Array.isArray(value)) {
      return value.join(', ') // 数组转字符串
    } else if (value.hasOwnProperty('label')) {
      return value.label // 对于有label属性的对象
    } else {
      return JSON.stringify(value) // 其他对象转JSON字符串
    }
  }
  
  // 处理布尔值
  if (typeof value === 'boolean') {
    return value ? '是' : '否'
  }
  
  // 处理枚举值
  if (props.item.options && Array.isArray(props.item.options)) {
    const option = props.item.options.find(opt => opt.value === value)
    if (option) {
      return option.label
    }
  }
  
  // 默认返回原值
  return value.toString()
}
</script>

<style scoped>
.render-form-item {
  width: 100%;
}

.display-value {
  padding: 4px 0;
  color: #606266;
}

:deep(.el-upload--picture-card) {
  width: 80px;
  height: 80px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 80px;
  height: 80px;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .render-form-item {
    width: 100%;
  }
  
  :deep(.el-select),
  :deep(.el-input),
  :deep(.el-date-editor),
  :deep(.el-time-picker) {
    width: 100%;
  }
}
</style>